/*新增费用*/
import React, { Component } from 'react';
import {
	StyleSheet, Text, View, Image, TouchableOpacity,
	PixelRatio, TextInput, Modal, ScrollView, Alert
} from "react-native";
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import ValidateDataUtil from '../../../../utils/ValidateDataUtil';
import { TitleView } from '../_components/TitleView.js';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import { Common } from '../../../../component/common/Common.js'
import { Item } from 'native-base';
import ToastUtil from '../../../../utils/toast';
import OrderAPIService from '../_common/OrderAPIService';
import MethodUtil from '../../../../utils/MethodUtil'
const scale = GLOBAL.SCALE;
let orderId = '', orderType = '';
let mappingZeroList = [];
let timer1, timer2;
export class ReportAssociatePage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		const { params } = navigation.state;
		let titleName = '关联' + (params.orderType == 'P' ? '销售' : '采购') + '成交报告';
		return {
			headerTitle: titleName,
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};
	constructor(props) {
		super(props);
		let { params } = props.navigation.state;
		orderId = params.orderId;
		orderType = params.orderType;
		this.state = {
			associateList: [],
			status: 'data',   // 状态 
			buttonDisable: true,
			searval: ''
		}
	}

	componentWillMount () {
		clearTimeout(timer1);
		clearTimeout(timer2);
		this._getAssociateTypeList();
	}

	//获取关联信息
	async _getAssociateTypeList () {
		this.setState({ status: 'loading' })
		let respData = await OrderAPIService.getMapedList({ orderId, queryType: 'ORDER_MAPPING_LIST' });
		respData && respData.map(item => {
			item.totalNoMappingQ = this._strToNumber(item.noMappingQuantity);
			item.orderMappingList.map(MItem => {
				item.totalNoMappingQ += this._strToNumber(MItem.quantity);
			})
		})
		console.log(respData, 'respData--------------totalNoMappingQ')
		this.setState({ associateList: respData, status: 'data' });
	}

	//跳转列表
	_goReportlistPage = (item) => {
		this.props.navigation.navigate('ReportListPage', {
			orderId: orderId,
			orderType: orderType,
			prodItem: item,
			type: 'ReportAssociatePage',
			isZXY: this.isZXY,
			callBack: (data) => {
				let mappedQ = 0;
				data.orderMappingList.map(item => {
					item.quantity = item.paramsQ ? item.paramsQ : '';
					mappedQ += this._strToNumber(item.quantity);
					console.log(mappedQ, 'mappedQ')
				})
				console.log(mappedQ, 'mappedQ-----------')
				let { associateList } = this.state;
				associateList.map(item => {
					if (item.itemId == data.itemId) {
						item = data;
						console.log(item.totalNoMappingQ, 'item.totalNoMappingQ')
						item.noMappingQuantity = MethodUtil.countObj.subtract(this._strToNumber(item.totalNoMappingQ), mappedQ);
					};
				})
				this.setState({ associateList });
			}
		});
	}

	//删除关联
	_delOrderM = (index, mIndex) => {
		let { associateList } = this.state;
		let { quantity } = associateList[index].orderMappingList[mIndex];
		let { noMappingQuantity } = associateList[index];
		noMappingQuantity = MethodUtil.countObj.add(this._strToNumber(noMappingQuantity), this._strToNumber(quantity));
		associateList[index].orderMappingList.splice(mIndex, 1);
		associateList[index].noMappingQuantity = noMappingQuantity;
		this.setState({ associateList });
	}

	_strToNumber = (str) => {
		str = Number.parseFloat(str) || 0;
		return str;
	}

	async _delMapping (subData) {
		let saveData = await OrderAPIService.mapDel(subData);
	}

	//加
	_increase = (index, mIndex, number, oldQ, currNoMappingQ, selectNoMappingQ) => {
		let { associateList } = this.state;
		let { quantity } = associateList[index].orderMappingList[mIndex];
		quantity = this._strToNumber(quantity);
		quantity = MethodUtil.countObj.add(quantity, number);
		if (this.validateQuatity(quantity, oldQ, currNoMappingQ, selectNoMappingQ)) {
			this.quantityAssignment(index, mIndex, quantity, oldQ)
		} else {
			this.quantityAssignment(index, mIndex, oldQ, oldQ)
		}
	}

	//减
	_decrease = (index, mIndex, number, oldQ) => {
		let { associateList } = this.state;
		let { quantity } = associateList[index].orderMappingList[mIndex];
		quantity = this._strToNumber(quantity);
		quantity = MethodUtil.countObj.subtract(quantity, number);
		if (quantity < 0) quantity = 0;
		this.quantityAssignment(index, mIndex, quantity, oldQ)
	}

	//数量验证
	validateQuatity = (qua, oldQ, currNoMappingQ, selectNoMappingQ) => {
		currNoMappingQ = MethodUtil.countObj.add(oldQ, this._strToNumber(currNoMappingQ));
		let minMQ = currNoMappingQ > this._strToNumber(selectNoMappingQ) ? this._strToNumber(selectNoMappingQ) : currNoMappingQ;
		if (qua > minMQ) {
			ToastUtil.showWarning('当前可关联量不能>' + minMQ);
			return false;
		}
		return true;
	}

	//数量赋值
	quantityAssignment = (index, mIndex, newQ, oldQ) => {
		let { associateList } = this.state;
		let { noMappingQuantity } = associateList[index];
		noMappingQuantity = MethodUtil.countObj.subtract(MethodUtil.countObj.add(this._strToNumber(noMappingQuantity), oldQ), this._strToNumber(newQ));
		associateList[index].orderMappingList[mIndex].quantity = newQ;
		associateList[index].noMappingQuantity = noMappingQuantity;
		this.setState({ associateList })
	}

	//保存
	async _save () {
		let { associateList } = this.state;

		let orderMappingList = [];
		associateList.map(item => {
			item.orderMappingList.map(oM => {
				oM.goodsId = item.goodsId;
				/**
				 * 采购关联销售 即orderType==P时，batchNo为item下的batchNo
				 * 销售关联采购 即orderType==S时，batchNo为mappingList下的batchNo
				*/
				if (orderType == 'P') {
					oM.batchNo = item.batchNo;
					oM.mappingId = oM.mappingId || '';
					oM.salesOrderId = oM.salesOrderId;
					oM.salesOrderItemId = oM.salesOrderItemId;
					oM.purchaseOrderId = item.orderId;
					oM.purchaseOrderItemId = item.itemId;
				} else {
					oM.batchNo = oM.batchNo;
					oM.mappingId = oM.mappingId || '';
					oM.purchaseOrderId = oM.purchaseOrderId;
					oM.purchaseOrderItemId = oM.purchaseOrderItemId;
					oM.salesOrderId = item.orderId;
					oM.salesOrderItemId = item.itemId;
				}

				//清除关联量为0的数据
				console.log(Number.parseFloat(oM.quantity))
				if (Number.parseFloat(oM.quantity) > 0) {
					orderMappingList.push(oM);
				}
			});
		})
		this.setState({ status: 'loading' })
		let saveData = await OrderAPIService.mapAdd({ submitStep: 'ADD_ORDER_MAPPING', orderInfo: { orderId: orderId }, orderMappingList });
		this.setState({ status: 'data' })
		if (saveData) {
			ToastUtil.showSuccess('关联成交报告保存成功').then(() => {
				this.props.navigation.state.params.callBack();
				this.props.navigation.goBack();
			})
		}

	}

	render () {
		let { associateList, status, searval } = this.state;
		return (
			<View style={styles.container}>
				<ScrollView>
					{associateList && associateList.map((item, index) => {
						return <View style={styles.boxWrap} key={index}>
							<Text style={[styles.companyName, { fontSize: 13 * scale }]}>订单编号：{item.orderId}</Text>
							<TouchableOpacity style={styles.prodItem} onPress={() => {
								this._goReportlistPage(item);
							}} >
								<Text style={styles.leftCount}>{item.goodsName + ':' + item.quantity + item.uomName}</Text>
								<View style={styles.rightBox}>
									<Text tyle={{ fontSize: 13 * scale, }}>未关联：</Text>
									<Text style={{ fontSize: 13 * scale, color: 'red', paddingRight: 12 * scale, }}>{
										(item.noMappingQuantity > 0 ? item.noMappingQuantity : 0) + item.uomName
									}</Text>
									<Image style={{ width: 6 * scale, height: 11 * scale }} source={require('../../../../imgs/arrow-left.png')} />
								</View>
							</TouchableOpacity>
							{
								//关联成交报告数量填写
								item.orderMappingList && item.orderMappingList.map((mOrder, mIndex) => {
									const finalQuantity = item.orderType === 'S' ? mOrder.purchaseNoMappingQuantity : mOrder.salesNoMappingQuantity;
									console.log(233, mOrder.quantity);
									return <View style={styles.associatedItem} key={mIndex}>
										<Text style={[styles.textStyle, { fontSize: 13 * scale }]}>
											订单编号：{item.orderType === 'S' ? mOrder.purchaseOrderId : mOrder.salesOrderId}
										</Text>
										<TouchableOpacity style={styles.deleteIcon} onPress={() => {
											this._delOrderM(index, mIndex);
										}} >
											<Image source={require('../../../../imgs/global/delete.png')} />
										</TouchableOpacity>
										<Text style={styles.textStyle}>{item.goodsName + '  可关联'}：{finalQuantity + item.uomName}</Text>

										<View style={{ position: 'relative' }} >
											<Text style={[styles.textStyle]}>可填数量</Text>
											<View style={{ flexDirection: 'row', alignItems: 'center', position: 'absolute', right: 0, bottom: 5 * scale, }} >
												<TouchableOpacity onPress={() => {
													let oldQ = this._strToNumber(mOrder.quantity);
													this._decrease(index, mIndex, 1, oldQ);
												}} >
													<Image style={styles.operIcon} source={require('../../../../imgs/global/decrease.png')} />
												</TouchableOpacity>

												<TextInput underlineColorAndroid="transparent" style={styles.listInput}
													ref={"accountInput" + mOrder.batchNo + mIndex}
													value={mOrder.quantity + ''}
													onChangeText={(text) => {
														let oldQ = this._strToNumber(mOrder.quantity);
														if (this.validateQuatity(this._strToNumber(text || 0), oldQ, item.noMappingQuantity, finalQuantity)) {
															mOrder.quantity = text;
															this.quantityAssignment(index, mIndex, mOrder.quantity, oldQ)
														} else {
															let fieldName = "accountInput" + mOrder.batchNo + mIndex;
															console.log(fieldName, '--------------------filedName')
															// mOrder.quantity = oldQ;
															clearTimeout(timer1)
															clearTimeout(timer2)
															timer1 = setTimeout(() => { this.refs[fieldName].clear(); }, 10);
															timer2 = setTimeout(() => { this.quantityAssignment(index, mIndex, mOrder.quantity, oldQ) }, 50);
														}
													}} />
												<TouchableOpacity onPress={() => {
													let oldQ = this._strToNumber(mOrder.quantity);
													this._increase(index, mIndex, 1, oldQ, item.noMappingQuantity, finalQuantity);
												}} >
													<Image style={styles.operIcon} source={require('../../../../imgs/global/increase.png')} />
												</TouchableOpacity>
											</View>
										</View>
										<Text style={[styles.textStyle]}>出库地点：{item.orderType === 'S' ? mOrder.purchaseDeliveryAddressName : mOrder.salesDeliveryAddressName}</Text>
									</View>
								})
							}
						</View>
					})}
				</ScrollView>
				<View style={{ width: '100%', height: 60 * scale, flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}>
					<TouchableOpacity onPress={() => { this._save() }} style={[styles.btnSave, styles.mtp9]}>
						<Text style={styles.btnSaveText}>保存</Text>
					</TouchableOpacity>
				</View>
				{
					status != 'data' ? (<View style={styles.statusStyle}><PageStatusIndex status={status} /></View>) : null
				}
			</View>
		)
	}
}
const styles = StyleSheet.create({
	container: {
		marginTop: 20 * scale,
		flex: 1,
		backgroundColor: style.color.white,
	},
	boxWrap: {
	},
	prodItem: {
		flexDirection: 'row',
		alignItems: 'center',
		height: 51 * scale,
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.border,
		position: 'relative',
		paddingLeft: 16 * scale,
		paddingRight: 16 * scale,
		paddingBottom: 11 * scale,
	},
	leftCount: {
		fontSize: 13 * scale,
		color: style.color.black,
		width: 230 * scale,
		paddingTop: 11 * scale,
	},
	rightBox: {
		// width: 85 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		position: 'absolute',
		right: 12 * scale,
		top: 3 * scale,
		bottom: 0,
		margin: 'auto',
	},
	associatedItem: {
		backgroundColor: '#F7F7F7',
		position: 'relative',
		marginLeft: 12 * scale,
		marginRight: 12 * scale,
		marginTop: 12 * scale,
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
		paddingTop: 12 * scale
	},
	deleteIcon: {
		position: 'absolute',
		right: 12 * scale,
		top: 20 * scale,
	},
	listInput: {
		paddingLeft: 10 * scale,
		height: 30 * scale,
		paddingVertical: 0,
		width: 101 * scale,
		borderColor: style.color.border,
		borderWidth: 1,
		marginLeft: 6 * scale,
		marginRight: 6 * scale
	},
	companyName: {
		fontSize: 13 * scale,
		marginTop: 8 * scale,
		height: 42 * scale,
		lineHeight: 42 * scale,
		paddingLeft: 16 * scale,
	},
	textStyle: {
		fontSize: 12 * scale,
		color: style.color.darkGray,
		marginBottom: 13 * scale
	},
	operIcon: {
		width: 30 * scale,
		height: 30 * scale
	},
	btnSaveText: {
		color: style.color.white,
		fontSize: 18 * scale,
		lineHeight: 44 * scale,
		textAlign: 'center',
	},
	btnSave: {
		width: 345 * scale,
		height: 44 * scale,
		backgroundColor: style.color.themeColor,
		borderRadius: 22 * scale,
		position: 'absolute',
		bottom: 0
	},
	mtp9: {
		marginTop: 9 * scale,
		marginBottom: 9 * scale
	},
	statusStyle: {
		flex: 1,
		position: 'absolute',
		height: '100%',
		width: '100%',
		top: 0,
		left: 0,
		flexDirection: 'column',
		justifyContent: 'center',
		alignItems: 'center'
	},
})
